from flask import Blueprint

from controllers import R
from mauth import HasPerm
from models.config import Config
from services.config_service import ConfigService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.config_validator import ConfigForm

# 声明一个蓝图
config = Blueprint('config', __name__, url_prefix="/sys/config")

# 声明一个配置业务服务
config_service = ConfigService(model=Config)


@config.route("/detail", methods=['POST'])
@HasPerm(access="sys:config:detail", name="通过id获取配置信息")
def config_detail():
    """
    通过id获取配置信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = Config.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = config_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@config.route("/page", methods=['POST'])
@HasPerm(access="sys:config:page", name="分页查询配置列表")
def config_page():
    """
    分页查询配置列表
    :return:
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(config_service.page(form))


@config.route("/save", methods=['POST'])
@HasPerm(access="sys:config:save", name="添加配置")
def config_save():
    """
    添加配置
    :return:
    """
    form = ConfigForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    config_service.save(form)
    return R.success("添加配置成功")


@config.route("/update", methods=['POST'])
@HasPerm(access="sys:config:update", name="修改配置")
def config_update():
    """
    修改配置
    :return:
    """
    form = ConfigForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    config_service.update(form)
    return R.success("修改配置成功")


@config.route("/remove", methods=['POST'])
@HasPerm(access="sys:config:remove", name="删除配置")
def config_remove():
    """
    删除配置
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    config_service.remove(form)
    return R.success("删除配置成功")
